package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import androidx.fragment.app.Fragment;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.example.myapplication.adapter.ViewPagerAdapter;
import com.example.myapplication.databinding.ActivityMainBinding;
import com.example.myapplication.util.Network;
import com.example.myapplication.util.TagUtil;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends AppCompatActivity {
    //分类数据
    private final Map<String, String> map = new HashMap<>(Network.getNewsSortList());
    private final String TAG = "MainActivity";
    private ActivityMainBinding viewBinding;
    private final Context context = MainActivity.this;
    //新闻分类文本
    List<String> newSort1List = new ArrayList<>();
    //新闻分类ID
    List<String> newSort2List = new ArrayList<>();
    List<Fragment> fragmentList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding = com.example.myapplication.databinding.ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());
        setData();
        initData();
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(TagUtil.BROADCAST_NAME));
    }

    // 广播接收端
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: 接收服务");
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Serializable serializable = bundle.getSerializable(TagUtil.BROADCAST_SERIALIZABLE_DATA);
                //接收到的数据
                List<String> userData = (List<String>)serializable;

                //清空newSort1List并重新设置数据
                newSort1List.clear();
                newSort1List.addAll(userData);

                //清空newSort2List并重新设置数据
                newSort2List.clear();
                for (String title : newSort1List) {
                    newSort2List.add(map.get(title));
                }
                //刷新UI
                refreshViewPagerAndTabs();
            }

        }
    };

    //根据新设置的新闻分类刷新UI
    private void refreshViewPagerAndTabs() {
        // 清空旧Fragment列表
        fragmentList.clear();

        // 重新生成Fragment实例（携带新分类Key）
        for (String key : newSort2List) {
            fragmentList.add(MyFragment.newInstance(key));
        }

        // 重置ViewPager适配器
        ViewPagerAdapter newAdapter = new ViewPagerAdapter(
                getSupportFragmentManager(),
                getLifecycle(),
                fragmentList
        );
        viewBinding.viewPage.setAdapter(newAdapter);

        // 重新绑定TabLayout（需先解绑旧监听器）
        new TabLayoutMediator(viewBinding.tab, viewBinding.viewPage,
                (tab, position) -> tab.setText(newSort1List.get(position))
        ).attach();
        //设置是否均分父容器宽度
        setTabStyle(viewBinding.tab.getTabCount());

    }

    /**
     * @param menu 定义的xml文件
     * @return
     * 重新添加菜单
     */

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    //菜单按钮点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_setting:
                Intent intent = new Intent(context,SettingSortActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("newsData", (Serializable) newSort1List);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initData() {
        //为每一个新闻类型创建Fragment
        fragmentList = new ArrayList<>();
        for (int i = 0; i < newSort1List.size(); i++) {
            //传递新闻类型
            MyFragment fragment = MyFragment.newInstance(newSort2List.get(i));
            fragmentList.add(fragment);
        }

        ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), getLifecycle(), fragmentList);
        viewBinding.viewPage.setAdapter(pagerAdapter);

        //绑定
        new TabLayoutMediator(viewBinding.tab, viewBinding.viewPage, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(newSort1List.get(position));
            }
        }).attach();

        //设置是否均分父容器宽度
        setTabStyle(viewBinding.tab.getTabCount());

        //检查设备是否联网
        if (isNetworkAvailable(context)){
            dialog(true);
            Log.d(TAG, "onCreate: 有网络权限");
        }else{
            dialog(false);

            Log.d(TAG, "onCreate: 没有网络权限");
        }

    }

    private void dialog(boolean flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.intent_dialog_title);
        if (flag){
            builder.setMessage(R.string.intent_dialog_true);
        }else{
            builder.setMessage(R.string.intent_dialog_false);
        }
        builder.setPositiveButton("确定", null);
        builder.show();
    }

    //设置tab显示宽度
    private void setTabStyle(int tabCount) {
        //小于6个设置自动均分父容器宽度
        if (tabCount <= 6){
            viewBinding.tab.setTabMode(TabLayout.MODE_FIXED);
        }else{
            viewBinding.tab.setTabMode(TabLayout.MODE_SCROLLABLE);
        }
    }

    //获取SP中的数据
    private void setData() {
        SharedPreferences sp  = getSharedPreferences(TagUtil.NEWS_SORT_PREFS, MODE_PRIVATE);
        if (!sp.contains(TagUtil.NEWS_SORT_PREFS_LIST)){
            System.out.println("sp不存在");
            for (Map.Entry<String,String> entry : map.entrySet()){
                newSort1List.add(entry.getKey());
                newSort2List.add(entry.getValue());
            }

            Gson gson = new Gson();
            //将newSort1List对象序列化为JSON字符串str
            String str = gson.toJson(newSort1List);
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(TagUtil.NEWS_SORT_PREFS_LIST,str);
            edit.commit();

        }else{
            System.out.println("sp存在,读取数据");
            String listJson1 = sp.getString(TagUtil.NEWS_SORT_PREFS_LIST, "");
            if (!listJson1.equals("")) {
                Gson gson = new Gson();
                //反序列化
                newSort1List = gson.fromJson(listJson1, new TypeToken<List<String>>() {
                }.getType());
            }
            for (int i = 0; i < newSort1List.size(); i++) {
                newSort2List.add(map.get(newSort1List.get(i)));
            }
            //获取到的数据
            for (int i = 0; i < newSort1List.size(); i++) {
                Log.d(TAG, "setData: newSort1List = " + newSort1List + ":" + newSort1List);
            }
            //获取到的数据
            for (int i = 0; i < newSort2List.size(); i++) {
                Log.d(TAG, "setData: newSort2List = " + newSort2List + ":" + newSort2List);
            }


        }
    }

    // 检查设备是否联网
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnected();
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        //取消注册广播
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
        super.onDestroy();
    }
}